package com.qsmx.store.core.net;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.qsmx.store.core.fusion.FusionCode;
import com.qsmx.store.core.util.Md5Util;
import com.qsmx.store.core.util.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.WeakHashMap;

/**
 * 文 件 名:
 * 描    述:
 * 创 建 人:  Xian
 * 创建时间:  2016/7/5 0005 下午 3:28
 */
public class BaseRequestWrapper {
    private WeakHashMap<String, Object> map;
    private JSONObject jsonParams;

    /**
     * 基础请求封装器
     */
    public BaseRequestWrapper(JSONObject params) {
        jsonParams = new JSONObject();
        JSONObject jsonHeader = new JSONObject();
        jsonHeader.put("portType", "APP");
        jsonHeader.put("timeStamp", StringUtil.getDateByTimestamp(System.currentTimeMillis()));
        jsonParams.put("body", params);
        jsonParams.put("header", jsonHeader);
    }

    public void put(WeakHashMap<String, Object> param) {
        map.putAll(param);
    }

    /**
     * 基础请求封装器
     */
    public BaseRequestWrapper() {
        map = new WeakHashMap<String, Object>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        map.put("timestamp", str);
    }

    public WeakHashMap<String, Object> sign() {
        List<String> list = new ArrayList<>();
        for (String str : map.keySet()) {
            list.add(str);
        }
        String[] paramNames = new String[list.size()];
        paramNames = list.toArray(paramNames);
        Arrays.sort(paramNames);
        String sign = FusionCode.SIGN_KEY;
        for (String paramName : paramNames) {
            if (!TextUtils.isEmpty((CharSequence) map.get(paramName))) {
                sign += paramName + map.get(paramName);
            }
        }
        sign += FusionCode.SIGN_KEY;
        try {
            sign = Md5Util.md5(sign);
            map.put("sign", sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
